package Interfaz;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import models.Empleados;

import org.hibernate.Session;

import tests.TestInsertEmpleados;

import connection.HibernateUtil;

public class LoginWindow extends JFrame implements KeyListener {

	/**
	 * UID que exige JFRAME para no dar Warning U_u
	 */
	private static final long serialVersionUID = 5029263600126560327L;

	JPanel panel;
	JLabel dniLbl;
	JLabel passLbl;
	JButton loginBtn;
	public JTextField dniText;
	public JPasswordField passText;
	JLabel image;
	public Session DAO;
	public static LoginWindow exec;
	
	/**
	 * Primer !!->[Y UNICO]<-!! main de la aplicaci�n
	 * 
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		exec = new LoginWindow();
		exec.initJFrameComponents();
		exec.setListeners();
	}
	public LoginWindow(){
	}
	/**
	 * Inicializa e instancia todos los elementos JFrame y otras variables
	 */
	public void initJFrameComponents() {
		// Instanciar declaraciones
		panel = new JPanel();
		dniLbl = new JLabel("D.N.I.");
		passLbl = new JLabel("Contrase�a");
		loginBtn = new JButton("Acceder");
		dniText = new JTextField(9);
		dniText.setText("12345678q");
		passText = new JPasswordField();
		passText.setText("1234");
		passText.addKeyListener(this);
		image = new JLabel(new ImageIcon(getClass().getResource(
				"raw/logo_small.jpg")));
		try {
			DAO = HibernateUtil.configureSessionFactory().getCurrentSession();
			DAO.beginTransaction();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Error al conectar a la DB");
			System.exit(0);
		}
		
		// Instanciar declaraciones END//
		// Asignar propiedades
		this.setTitle("MyBolos -ERP-> Login");
		image.setBounds(90, 0, 200, 200);
		dniLbl.setBounds(10, 210, 50, 25);
		passLbl.setBounds(10, 245, 70, 25);
		dniText.setBounds(100, 210, 290, 25);
		passText.setBounds(100, 245, 290, 25);
		dniText.setBorder(BorderFactory.createLineBorder(new Color(0xCCCCCC), 1));
		passText.setBorder(BorderFactory.createLineBorder(new Color(0xCCCCCC),
				1));
		loginBtn.setBounds(163, 330, 85, 25);
		loginBtn.setBackground(new Color(0xCCCCCC));
		// A�adir a la interfaz los elementos swing
		this.add(image);
		this.add(dniLbl);
		this.add(passLbl);
		this.add(passText);
		this.add(dniText);
		this.add(loginBtn);
		// A�adir a la interfaz los elementos swing END//
		// Con las siguientes dos lineas colocamos la ventana en el CENTRO de la
		// pantalla
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		this.setBounds(((d.width / 2) - 200), ((d.height / 2) - 200), 400, 400);
		panel.setBackground(Color.WHITE);
		this.add(panel);
		this.setBackground(Color.WHITE);
		this.setVisible(true);
		this.setResizable(false);
	}

	/**
	 * M�todo que se encarga de a�adir los listeners a los botones se separa
	 * para tener mayor claridad y no tener "embutidos de codigo"
	 */
	public void setListeners() {
		loginBtn.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				doLogin();
			}
		});
	}

	public boolean checkErrorsOnDNI(String dni) {
		boolean result = false;
		boolean result1 = false;
		boolean result2 = false;
		boolean result3 = false;
		String[] abecedario = { "a", "b", "c", "d", "e", "f", "g", "h", "i",
				"j", "k", "l", "m", "n", "�", "o", "p", "q", "r", "s", "t",
				"u", "v", "w", "x", "y", "z" };
		String[] numeros = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
		for (int a = 0; a < abecedario.length; a++) {
			if (dni.contains(abecedario[a])) {
				result1 = true;
				break;
			}
		}
		for (int a = 0; a < numeros.length; a++) {
			if (dni.contains(numeros[a])) {
				result2 = true;
				break;
			}
		}
		if (dni.length() == 9) {
			result3 = true;
		}
		if (result1 && result2 && result3)
			result = true;
		return result;
	}

	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub
		if(arg0.getKeyCode()==10){
			doLogin();
		}
	}

	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public Empleados doLogin(){
		Empleados empleado = null;
		String dni = dniText.getText();
		String pass = passText.getText();
		if (checkErrorsOnDNI(dni.toLowerCase())) {
			if (pass.length() != 0) {
				List<Empleados> empleados = DAO.createQuery("FROM Empleados WHERE dniEmp='"+dni+"' AND pass='"+pass+"'").list();
				if (empleados.size() !=0) {
					empleado = empleados.get(0);
					MenuWindow mw = new MenuWindow(empleados.get(0));
					exec.setVisible(false);
				} else {
					JOptionPane.showMessageDialog(null,
							"Dni o contrase�a incorrectos");
				}
			} else {
				JOptionPane.showMessageDialog(null,
						"Hay uno o varios errores en su Contrase�a");
			}
		} else {
			JOptionPane.showMessageDialog(null,
					"Hay uno o varios errores en su DNI");
		}
		return empleado;
	}
	public LoginWindow returnExec(){
		return exec;
	}
}
